package com.book.service;

import com.book.items.composite.AbstractProductItem;
import com.book.items.composite.ProductComposite;
import com.book.pojo.ProductItem;
import com.book.repo.ProductItemRepository;
import com.book.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: TODO
 * @date 2023/11/12 11:35
 */
@Service
public class ProductItemService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ProductItemRepository productItemRepository;


    public ProductComposite fetchAllItems(){
        Object items = redisUtils.get("items");
        if(!ObjectUtils.isEmpty(items)){
            return (ProductComposite) items;
        }
        List<ProductItem> fetchDbItems = productItemRepository.findAll();
        //将DB中的商品类目信息拼装成组合模式的树形结构
        ProductComposite productComposite = generateProductTree(fetchDbItems);
        if(null == productComposite){
            throw new RuntimeException("data is null");
        }
        redisUtils.set("items",productComposite,3600);
        return productComposite;
    }

    private ProductComposite generateProductTree(List<ProductItem> fetchDbItems) {
        List<ProductComposite> productComposites = new ArrayList<>(fetchDbItems.size());
        fetchDbItems.forEach(item-> productComposites.add(
                ProductComposite.builder().id(item.getId())
                        .name(item.getName()).pid(item.getPid()).build()
        ));
        Map<Integer, List<ProductComposite>> groupList = productComposites.stream().collect(Collectors.groupingBy(ProductComposite::getPid));
        productComposites.stream().forEach(item->{
            List<ProductComposite> productComposites1 = groupList.get(item.getId());
            item.setChild(productComposites1 == null?new ArrayList<>():productComposites1.stream().map(o->(AbstractProductItem)o).collect(Collectors.toList()));

        });
        ProductComposite composite = productComposites.size() == 0 ? null: productComposites.get(0);
        return composite;


    }


}
